package couchdb

import (
	"context"
	_ "github.com/go-kivik/couchdb/v3" // The CouchDB driver
	"github.com/go-kivik/kivik/v3"
)

// Config KMS Server's database config
type Config struct {
	Dsn      string `help:"couchDB连接地址" default:"http://admin:123456@localhost:5984/"`
	Database string `help:"couchDB数据库" default:"kms"`
}

type DB struct {
	*kivik.DB
}

func NewDB(conf *Config) (*DB, error) {
	client, err := kivik.New("couch", conf.Dsn)
	if err != nil {
		return nil, err
	}
	ctx := context.Background()
	ok, err := client.DBExists(ctx, conf.Database)
	if err != nil {
		return nil, err
	}
	if !ok {
		err = client.CreateDB(ctx, conf.Database, map[string]interface{}{"partitioned": true})
	}
	if err != nil {
		return nil, err
	}
	return &DB{
		client.DB(context.TODO(), conf.Database),
	}, nil
}
